package py.com.fms.com.session.transactions;

// External classes imports 
// Java Classes
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

// Seam Classes
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage.Severity;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.richfaces.component.html.HtmlDatascroller;

import com.ibatis.sqlmap.client.SqlMapClient;

import javax.faces.application.FacesMessage;
import javax.faces.event.ActionEvent;
import javax.faces.validator.ValidatorException;

//project classes imports
import py.com.fms.com.bean.BuyConditionBean;
import py.com.fms.com.bean.OrderDetBean;
import py.com.fms.com.bean.OrderHeadBean;
import py.com.fms.com.bean.PurchasesDetBean;
import py.com.fms.com.bean.SupplyCostStockBean;
import py.com.fms.com.persistence.services.OrderServices;
import py.com.fms.com.persistence.services.SupplyCostStockServices;
import py.com.fms.fms.bean.EnterpriseBean;
import py.com.fms.fms.bean.SupplierBean;
import py.com.fms.fms.bean.UsersBean;
import py.com.fms.com.persistence.services.BuyConditionServices;
import py.com.fms.fms.persistence.services.CurrencyServices;
import py.com.fms.fms.persistence.services.EnterpriseServices;
import py.com.fms.fms.persistence.services.IvaServices;
import py.com.fms.fms.persistence.services.QuotationServices;
import py.com.fms.fms.persistence.services.UsersServices;
import py.com.fms.fms.session.maintenances.EditNumbers;
import py.com.fms.exception.CommonException;
import py.com.fms.session.ComAssistant;
import py.com.fms.session.ParamHolder;
import py.com.fms.session.ServiceSqlMap;
import py.com.fms.session.WithinHolder;
import py.com.fms.session.modalSelectHolder;
import py.com.fms.utilities.ConvertAssistant;
import py.com.fms.utilities.DateAssistant;

@SuppressWarnings("unused")
@Name("trnPurchaseOrder")
@Scope(ScopeType.SESSION)
public class TrnPurchaseOrder {

	private FacesMessages facesMessages;
	@Logger
	private Log log;
	@In("#{serviceSqlMap}")
	private ServiceSqlMap sqlMap;
	private boolean editMode;
	private String initVar;
	private Date today = null;

	// Task Attendees Attributes 
	@In("#{withinHolder}")
	private WithinHolder aid;
	@In("#{paramHolder}")
	private ParamHolder param;
	@In("#{convertAssist}")
	private ConvertAssistant convert;
	@In("#{comAssist}")
	private ComAssistant comAssist;
	@In Credentials credentials;
	@In Identity identity;
	private UsersBean user;
	
	// Attribute used for saving and deleting
	private OrderHeadBean orderHead;
	private OrderDetBean orderDet;
	private BuyConditionBean buyCondition;
	private EditNumbers numbers;
	
	// Grilla detalle
	private List<OrderDetBean> allOrderDet;
	
	
	// Services
	private EnterpriseServices enSrv;
	private OrderServices orSrv;
	private BuyConditionServices bcSrv;
	private IvaServices txSrv;
	private QuotationServices qtSrv;
	private CurrencyServices crSrv;
	private UsersServices usSrv;
	private SupplyCostStockServices scstSrv;
	
	// Collection of monedasBean
	private Collection<BuyConditionBean> allBuyCondition;

	// Attribute used for editing or updating
	
	
	// Query
	// Flag that indicates if we are doing a query operation
	private Boolean queryOperation = false;
	
	// For Query of all Orders
	private OrderHeadBean orderQueryHead;
	private OrderDetBean orderQueryDet;
	private Collection<OrderHeadBean> allOrderQueryHead;
	private Collection<OrderDetBean> allOrderQueryDet;
	
	// For Orders Cancellation
	private OrderHeadBean orderCancelHead;
	private OrderDetBean orderCancelDet;
	private Collection<OrderHeadBean> allOrderCancelHead;
	private Collection<OrderDetBean> allOrderCancelDet;
	
	// For Orders Confirmation
	private OrderHeadBean orderConfHead;
	private OrderDetBean orderConfDet;
	private Collection<OrderHeadBean> allOrderConfHead;
	private Collection<OrderDetBean> allOrderConfDet;
	
//	Necessary Attributes;
	private static Boolean canSave;
	private EnterpriseBean entName = null;
	private EnterpriseBean entCod;
	private Long entId;
	private Boolean validateEntireForm = true;
	
	// RichFaces dataScroller variables
	private modalSelectHolder selectHolder;
	private HtmlDatascroller scroller = new HtmlDatascroller();
	private Integer scrollerPage = new Integer(0);
	private Boolean selectedAll = false;

	
	/**
	 * [[[[[[[[[[[[ Methods ]]]]]]]]]]]] 
	 * [[[[[[[[[[-------------]]]]]]]]]]
	 * @throws CommonException 
	 */

	/**
	 * This method is used for class initializing 
	 */
	public void initData() throws CommonException {

		System.out.println("Initialization Flag = " + this.getInitVar());

		if ("S".equals(this.getInitVar())) {
			System.out.println("INITIALIZING DATA ------------------");
			this.loadUserData();
			this.initBeans();
			this.initServices();
			this.initAssistants();
			this.initCollections();
			this.loadDataGrid();
			this.initQueryObjects();

		}
		this.setInitVar(null);
		System.out.println("OUT");
				
	}
	
	/**
	 * Retrieve the data of the logged user 
	 * and store the data into a user object
	 * 
	 * @return      is a void method, just store the data into an object
	 */
	private void loadUserData() throws CommonException {
		System.out.println("Iniciando usuario compra");
		if (user == null) {
			user = new UsersBean();
		}
		if (usSrv == null) {
			usSrv = new UsersServices(this.sqlMap.getConfig());
		}
		System.out.println("Antes de credential");
		if (user != null && credentials != null) {
			System.out.println("Credenciales Encontradas: " + credentials + "User: " + user);
			this.getUser().setUserName(credentials.getUsername());
			System.out.println("User Name: " + this.getUser().getUserName());
			try {
				this.setUser(usSrv.getUserDataByName(this.getUser().getUserName().toUpperCase().trim()));
			} catch (Exception e) {
				System.out.println("ERROR: " + e.getMessage());
			}
			
			this.setUser(this.user);
			System.out.println("User: " + this.getUser());
			System.out.println("User ENT: " + this.getUser().getIdEnt());
			System.out.println("User BRANCH: " + this.getUser().getDefaultBranch());
		} else {
			System.out.println("Credenciales Nulas");
		}
		System.out.println("Despues de credentials");
	}
	
	public void loadParams() throws CommonException{
		this.param.initData();
		this.param.loadParams();
	}
	
	
	/**
	 * Initialize the entity Beans 
	 */
	public void initBeans(){
		if (orderHead == null){
			orderHead = new OrderHeadBean();
		}
		
		if (orderDet == null) {
			orderDet = new OrderDetBean(); 
		}	
		
		if (buyCondition == null){
			buyCondition = new BuyConditionBean();
			buyCondition.setStatus(true);
		}
		
        if (entCod == null){
			entCod = new EnterpriseBean();
		}
		
		if (entName == null){
			entName = new EnterpriseBean();
		}
		
		if(selectHolder == null){
			selectHolder = new modalSelectHolder();
		}

	}
	
	/**
	 * Initialize the services objects 
	 */
	public void initServices() throws CommonException{
		
		if (enSrv == null){
			enSrv = new EnterpriseServices(this.sqlMap.getConfig());
		}
		
		if (orSrv == null){
			orSrv = new OrderServices(this.sqlMap.getConfig());
		}
		
		if (bcSrv == null){
			bcSrv = new BuyConditionServices(this.sqlMap.getConfig());
		}
		
		if (txSrv == null){
			txSrv = new IvaServices(this.sqlMap.getConfig());
		}
		
		if (qtSrv == null){
			qtSrv = new QuotationServices(this.sqlMap.getConfig());
		}

		if (crSrv == null){
			crSrv = new CurrencyServices(this.sqlMap.getConfig());
		}

		if(scstSrv == null){
		   scstSrv = new SupplyCostStockServices(this.sqlMap.getConfig());
		}
		
	}
	
	/**
	 * Initialize the Assistants objects 
	 */
	public void initAssistants(){
		
		
		if(aid == null){
			aid = new WithinHolder();
		}
		
		if(param == null){
			param = new ParamHolder();
		}
		
		if(convert == null){
			convert = new ConvertAssistant();
		}
		
		if(comAssist == null){
			comAssist = new ComAssistant();
		}
		
		if (numbers == null){
			numbers = new EditNumbers();
		}

		
	}
	
	/**
	 * Initialize collection objects 
	 */
	public void initCollections(){
		if(allBuyCondition == null){
			allBuyCondition = new ArrayList<BuyConditionBean>();
		}
		
		if(allOrderDet == null){
			allOrderDet = new ArrayList<OrderDetBean>();
		}



	}
	
	/**
	 * Initialize Query objects 
	 */
	public void initQueryObjects(){
		
		if(orderQueryHead == null){
			orderQueryHead = new OrderHeadBean();
		}
		
		if(orderQueryDet == null){
			orderQueryDet = new OrderDetBean();
		}
		
		if(allOrderQueryHead == null){
			allOrderQueryHead = new ArrayList<OrderHeadBean>();
		}
		
		if(allOrderQueryDet == null){
			allOrderQueryDet = new ArrayList<OrderDetBean>();
		}
		
		if(orderCancelHead == null){
			orderCancelHead = new OrderHeadBean();
		}
		
		if(orderCancelDet == null){
			orderCancelDet = new OrderDetBean();
		}
		
		if(allOrderCancelHead == null){
			allOrderCancelHead = new ArrayList<OrderHeadBean>();
		}
		
		if(allOrderCancelDet == null){
			allOrderCancelDet = new ArrayList<OrderDetBean>();
		}
		
		if(orderConfHead == null){
			orderConfHead = new OrderHeadBean();
		}
		
		if(orderConfDet == null){
			orderConfDet = new OrderDetBean();
		}
		
		if(allOrderConfHead == null){
			allOrderConfHead = new ArrayList<OrderHeadBean>();
		}
		
		if(allOrderConfDet == null){
			allOrderConfDet = new ArrayList<OrderDetBean>();
		}

	}
	
	
	/**
	 * Clean all objects
	 */
	public void cleanData(){

		buyCondition = null;
		entCod = null;
		entName = null;
		user = null;
		
		enSrv = null;
		bcSrv = null;
		txSrv = null;
		usSrv = null;
		orSrv = null;
		qtSrv = null;
		crSrv = null;
		scstSrv = null;
		
		aid = null;
		param = null;
		convert = null;
		comAssist = null;
        
		allBuyCondition = null;
		allOrderDet = null;
		orderDet = null;
		orderHead = null;
		
		numbers = null;
		
		
	}
	
	public void cleanQuery(){
		
		// First we clean
		orderQueryHead = null;
		orderQueryDet = null;
		allOrderQueryHead = null;
		allOrderQueryDet = null;
		
		// The we initialize objects
		this.initQueryObjects();
		
	}
	
	public void cleanCancel(){
		
		// First we clean
		orderCancelHead = null;
		orderCancelDet = null;
		allOrderCancelHead = null;
		allOrderCancelDet = null;
		
		// The we initialize objects
		this.initQueryObjects();
		
	}
	
	public void cleanConfirm(){
		
		//First we clean
		orderConfHead = null;
		orderConfDet = null;
		allOrderConfHead = null;
		allOrderConfDet = null;
		
		// The we initialize objects
		this.initQueryObjects();
		
	}

	/**
	 * Retrieve all bean data and store it into a collection.
	 * Used to load a Grid in the Visual Layer
 	 */
	private void loadDataGrid() {
		try {
			this.setAllBuyCondition(bcSrv.getAllBuyCondition());
			for (BuyConditionBean buyCondition : this.getAllBuyCondition()) {
				System.out.println(buyCondition.getDescrip());
			}
		} catch (CommonException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Cancel Current operation and clean form objects.
 	 */
	public String cancelData() throws CommonException {
//		this.facesMessages.clear();
		this.setInitVar("S");
		this.cleanData();
		this.initData();
		return null;
	}
	
	public void selectAll(ActionEvent event) {
		System.out.println("SELECTING ALL CHECKBOXES");
		
		// get the current scroller page
		int page = Integer.valueOf(scrollerPage).intValue();
		if (page != 0) {
		    page = page - 1;
		}
		int start = page * 10;
		int stop = (page * 10) + 10;
		if (stop > this.getAllOrderDet().size()) {
		    stop = this.getAllOrderDet().size();
		}
		System.out.println("> page: " + page + "; start: " + start + "; stop: " + stop);
		System.out.println("Selected All: " + this.selectedAll);
		
		// check the boxes on the active page
		if(this.selectedAll == true){
			for (int i = start; i < stop; i++) {
				this.allOrderDet.get(i).setSelected(true);
			}
		}
		
		// uncheck the boxes on the active page
		if(this.selectedAll == false){
			for (int i = start; i < stop; i++) {
				this.allOrderDet.get(i).setSelected(false);
			}
		}
		
		
	}
	
	public void deleteSelected(){
		System.out.println("DELETING SELECTEDS");
		Iterator<OrderDetBean> it = this.allOrderDet.iterator();
		while(it.hasNext()){
			OrderDetBean next = it.next();
			if(next.getSelected().equals(true)){
				it.remove();
			}
		}
		if(this.selectedAll.equals(true)){
			this.setSelectedAll(false);
		}
		this.calcHeadAmounts();
		
	}
	
	
	/**
	 * Returns an Boolean object. 
	 * <p>
	 * This method handle the enabling of form objects
	 * that are dependents of the Supply . 
	 *
	 * @return      a Boolean Object
	 */
	public Boolean activeSupplyDepend(){	
		if(this.getOrderDet().getSupplyData() == null){
			System.out.println("RENDER TAX: TRUE");
			return true;
		}else{
			System.out.println("RENDER TAX: FALSE");
			return false;
		}
	}
	
	
	public void retrieveSupplyData() throws CommonException {
		System.out.println("RETRIEVING SUPPLY DATA");
		if (this.getOrderDet().getSupplyData() == null) {
			System.out.println("POR FAVOR ELIJA EL INSUMO");
		} else {
			Long taxId = new Long(0);
			taxId = this.getOrderDet().getSupplyData().getTax();
			this.getOrderDet().setTaxData(this.txSrv.getTaxData(taxId));
			if(this.getOrderDet().getMeasureUnitData() != null){
				this.retrieveSupplyCost();
			}
			System.out.println("TAX DATA: ".concat(this.getOrderDet().getTaxData().getId().toString()));
		}

	}

	public void retrieveChangeType() throws ParseException, CommonException {
		System.out.println("RETRIEVING CHANGE TYPE");
		// First we verify for null object
		if (this.getOrderHead().getCurrencyData() == null) {
			System.out.println("Currency Data is NULL");
		} else {
			// If object is not null
			// We retrieve the parameters
			Long localCurrency = this.crSrv.getIdCurrency("GUAR");
			Long idCurrency = this.getOrderHead().getCurrencyData().getId();
			if (idCurrency.equals(localCurrency)) {
				this.getOrderHead().setChangeType(new Double(1));
			} else {
				Date startDate = DateAssistant.getCurrentDate();
				System.out.println(" ##### CHANGE TYPE DATE: ".concat(startDate.toString()).concat(" ##### "));
				System.out.println(" ##### currency id = ".concat(idCurrency.toString()).concat(" ##### "));
				// Then we retrieve the changeType based on passed parameters
				Double changeType = (Double) this.qtSrv.getAmountQuotation(idCurrency, startDate);

				// And set the changeType value
				if (changeType == null) {
					FacesMessages.instance().add("La moneda seleccionada no tiene cotizaci�n para la fecha actual. Favor inserte cotizaci�n para la fecha.");
					this.getOrderHead().setChangeType(new Double(0));
				} else {
					this.getOrderHead().setChangeType(changeType);
					System.out.println("CHANGE TYPE: " + (this.getOrderHead().getChangeType()));
				}
			}
		}
	}
	
	public void retrieveSupplyCost(){
		if(this.getOrderDet().getSupplyData() == null || this.getOrderDet().getMeasureUnitData() == null){
			System.out.println("COST STOCK DATA Data is NULL");
		}else{
			try {
			// OOOOOOOOOOOJOOOOOOOOOOOOOOO SUCURSAL TRAER DEL FORMULARIOOOOOOOOOOOOOOOOOOOOOOOO
			Long supply = this.getOrderDet().getSupplyData().getId();
			Long branch = new Long(this.user.getDefaultBranch());
			Long measureUnit = this.getOrderDet().getMeasureUnitData().getId();
			// Retrieve Supply Cost Stock Data
			SupplyCostStockBean costStockData;
			costStockData = scstSrv.getSupplyCostStockData(supply, branch, measureUnit);
			if(costStockData != null){
				this.getOrderDet().setGrossCost(costStockData.getGrossCost());
			}else{
				this.getOrderDet().setGrossCost(null);
			}
			} catch (CommonException e) {
				// TODO Auto-generated catch block
				System.out.println(e.getMessage());
				e.printStackTrace();
			}
		}
	}
	
	public void selectSupplier(SupplierBean supplier){
		System.out.println("Selecting Supplier");
		this.getOrderHead().setSupplierData(null);
		if(supplier.getCod() == null){
			comAssist.generateErrorMsg("Favor seleccione un proveedor", "actionForm:orderAcceptSelectedSupplier");
		}else{
			System.out.println("Selecting Supplier: "+supplier.getCod());
			this.getOrderHead().setSupplierData(supplier);
		}	
	}
	
	/**
	 *  This method process the detail data and insert it into a collection. 
	 */
	public void insertDetail(){
		try{
			// First we validate the form
			this.comAssist.validateOrderDet(this.getOrderDet());

				System.out.println("Inserting Detail");
				System.out.println("SUPPLY: " + this.getOrderDet().getSupplyData().getCod());
				System.out.println("Bean: " + this.getOrderDet());
				if(this.getOrderDet() == null){
					System.out.println("Detail Bean is NULL");
				}else{
					// First we calculate the Net Cost
					System.out.println("GROSS COST: "+(this.getOrderDet().getGrossCost()));
					System.out.println("DISCOUNT: "+(this.getOrderDet().getDiscount()));
					System.out.println("CHARGE: "+(this.getOrderDet().getCharge()));
					this.getOrderDet().setNetCost(new BigDecimal((this.getOrderDet().getGrossCost().doubleValue())-(this.getOrderDet().getDiscount().doubleValue())+(this.getOrderDet().getCharge().doubleValue())));
					// Then we calculate the item total based in calculated net cost
					this.getOrderDet().setItemTotal(new BigDecimal((this.getOrderDet().getQuantity().doubleValue())*(this.getOrderDet().getNetCost().doubleValue())));
					
					// Processing Tax
					this.comAssist.processTax(this.getOrderDet().getTaxData(), this.getOrderDet().getItemTotal());
					
					// Setting tax fields
					this.getOrderDet().setTaxedTotal(this.comAssist.getTaxedTotal());
					this.getOrderDet().setExemptTotal(this.comAssist.getExemptTotal());
					this.getOrderDet().setTaxTotal(this.comAssist.getTaxTotal());
			
					// Calculating basic quantity
					this.getOrderDet().setBasicQuantities((this.getOrderDet().getMeasureUnitData().getQuantity())*(this.getOrderDet().getQuantity()));
					
					// Add the Object into a collection
					if(this.getOrderDet().getItemTotal().longValue() <= 0){
						System.out.println("TOTAL INVALIDO");
					}else{
						this.allOrderDet.add(this.getOrderDet());
						this.calcHeadAmounts();
						this.setOrderDet(null);
						this.setInitVar("S");
					}

			}
			
			
		} catch (Exception e) {
//					this.facesMessages.add(Severity.ERROR, e.getMessage());
		log.error(e);
		}
	}
	
	/**
	 *  Calculate the header amounts based in detail. 
	 */
	public void calcHeadAmounts(){
		
		// Initializing Variables
		Double totalAmount = new Double(0);
		
		// Defining an Iterator
		Iterator<OrderDetBean> it1 = allOrderDet.iterator();

		// Walking trough collection
		while (it1.hasNext()){
			// Setting the next reg
			OrderDetBean nextDet = it1.next();
			System.out.println("Next:" + nextDet);
			// Calculating the addition
			totalAmount += nextDet.getItemTotal().doubleValue();	
		}
		
		System.out.println("Total amount:" + totalAmount);	
		if(totalAmount == null || totalAmount <=0){
			System.out.println("Invalid Total:" + totalAmount);
		}else{
			// If addition is not null set the head total
			this.getOrderHead().setOrderTotal(new BigDecimal(totalAmount));
		}
	}
		

	/**
	 *  Save Data into database. 
	 */
	public void saveNewData() throws ParseException, SQLException {
		// save new data by Negento.
		this.setValidateEntireForm(true);
		Boolean validForm = comAssist.validateOrderHead(this.orderHead, this.allOrderDet);
		if(validForm == true){
			try {
				OrderHeadBean newOrderHead = new OrderHeadBean();
				OrderDetBean newOrderDet = new OrderDetBean();
				
				newOrderHead.setIdEnt(user.getIdEnt());
				this.numbers.setInitVar("S");
				this.numbers.initData();
				newOrderHead.setOrderNumber(this.numbers.getNumber(newOrderHead.getIdEnt(), "PED"));
				newOrderHead.setIdSupplier(this.orderHead.getSupplierData().getId());
				newOrderHead.setBuyType(this.orderHead.getBuyTypeData().getId()); //debito - credito
				newOrderHead.setOrderDate(DateAssistant.getHoleDateTime());
				newOrderHead.setLastUpdDate(DateAssistant.getHoleDateTime());
				newOrderHead.setDeliveryDate(this.orderHead.getDeliveryDate());
				
				System.out.println("THIS.ORDERHEAD.GETBUYCONDITIONDATA() = " + this.orderHead.getBuyConditionData().getId());
				System.out.println("this.orderHead.getCostCenterData() = " + this.orderHead.getCostCenterData().getId());
				System.out.println("this.orderHead.getCurrencyData() = " + this.orderHead.getCurrencyData().getId());
				System.out.println("this.orderHead.getChangeType() = " + this.orderHead.getChangeType());
				
				newOrderHead.setBuyCondition(this.orderHead.getBuyConditionData().getId());
				System.out.println("1");
				newOrderHead.setCostCenter(this.orderHead.getCostCenterData().getId());
				System.out.println("2");
				newOrderHead.setCurrency(this.orderHead.getCurrencyData().getId());
				System.out.println("3");
				newOrderHead.setChangeType(this.orderHead.getChangeType());
				System.out.println("4");
				newOrderHead.setOrderTotal(this.orderHead.getOrderTotal());
				System.out.println("5");
				newOrderHead.setDiscount(new BigDecimal(0));
				System.out.println("6");
				newOrderHead.setUserIns(this.user.getId());
				System.out.println("7");
				/**
				 * Estados del Pedido
				 * ------------------
				 * PEND = PENDIENTE DE PAGO
				 * ANUL = ANULADO
				 * CONF = CONFIRMADO
				 */
				newOrderHead.setStatus("PEND");
				System.out.println("8");
				orSrv.saveNewOrderHead(newOrderHead);
				System.out.println("9");
				Long idHead = new Long(0);
				System.out.println("10");
				idHead = orSrv.getOrderHeadIdByOrderNumber(newOrderHead.getIdEnt(), newOrderHead.getOrderNumber());
				System.out.println("11");
				int vContador = 0;
				for (OrderDetBean bean : allOrderDet) {
					vContador++;
					
					// Processing Tax
//					this.comAssist.processTax(this.getOrderDet().getTaxData(), this.getOrderDet().getItemTotal());
					System.out.println("###### vContador  #####" + vContador);
					
					// Setting Fields
					newOrderDet.setIdHead(idHead);
					newOrderDet.setItem(new Long(vContador));
					newOrderDet.setInvoiceQuantities(new Double(0));
					newOrderDet.setReceivedQuantities(new Double(0));
					newOrderDet.setSupply(bean.getSupplyData().getId());
					newOrderDet.setMeasureUnit(bean.getMeasureUnitData().getId());
					newOrderDet.setBasicQuantities(bean.getBasicQuantities());
					newOrderDet.setOldGrossCost(new BigDecimal(0));
					newOrderDet.setGrossCost(bean.getGrossCost());
					newOrderDet.setQuantity(bean.getQuantity());
					newOrderDet.setTax(bean.getTaxData().getId());
					newOrderDet.setTaxedTotal(bean.getTaxedTotal());
					newOrderDet.setExemptTotal(bean.getExemptTotal());
					newOrderDet.setTaxTotal(bean.getTaxTotal());
					newOrderDet.setDiscount(bean.getDiscount());
					newOrderDet.setCharge(bean.getCharge());
					newOrderDet.setItemTotal(bean.getItemTotal());
					newOrderDet.setNetCost(bean.getNetCost());
					
					orSrv.saveNewOrderDet(newOrderDet);
					FacesMessages.instance().add("Pedido Registrado de forma Exitosa");
					this.setValidateEntireForm(false);
					
				}
				this.cleanData(); // Cleaning Objects
				this.setInitVar("S"); // Setting initialization Flag	
				
			} catch (CommonException e) {
				// TODO: handle exception
//				this.facesMessages.add(Severity.ERROR, e.getMessage());
				System.out.println("NO SE PUDO INSERTAR. " + e.getMessage());
				
				log.error(e);
			}finally{
						
			}
		}else{
			System.out.println("Complete los campos correctamente");
		}
		
	}
	
	/**
	 *  Orders Query. 
	 * @throws SQLException 
	 * @throws SQLException 
	 */
	
	public void retrieveFilteredOrders() throws SQLException{
		try{
			Long idSupplier = null;
			String status = null;
			Date orderDate = null;
			
			if(this.getOrderQueryHead().getSupplierData() != null){
				idSupplier = this.getOrderQueryHead().getSupplierData().getId();
			}
			if(this.getOrderQueryHead().getStatus() != null){
				status = this.getOrderQueryHead().getStatus();
			}
			
			if(this.getOrderQueryHead().getOrderDate() != null){
				orderDate = this.getOrderQueryHead().getOrderDate();
			}
			
			this.setAllOrderQueryHead(orSrv.getFilteredOrders(idSupplier, status, orderDate));
			
			if(this.allOrderQueryHead.isEmpty()){
				this.comAssist.generateInfoMsg("No se encontraron Pedidos", "actionform:orQuerySearchBtn");
			}
			
		}catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());
			
			log.error(e);
		}
		
	}
	
	public void retrievePendingOrders(OrderHeadBean orderHeadp, String operation) throws SQLException{
		try{
			Long idSupplier = null;
			Date orderDate = null;
			String status = new String("PEND");
			if(orderHeadp.getSupplierData() != null){
				idSupplier = orderHeadp.getSupplierData().getId();
			}
			
			if(orderHeadp.getOrderDate() != null){
				orderDate = orderHeadp.getOrderDate();
			}
			if(operation.equals("CONFIRM")){
				this.setAllOrderConfHead(orSrv.getPendingOrders(idSupplier, orderDate, status));
				System.out.println("PENDING ORDER LIST CONFIRM: " + this.allOrderConfHead);
				if(this.allOrderConfHead.isEmpty()){
					this.comAssist.generateInfoMsg("No Existen Pedidos con estado Pendiente", "actionform:orConfSearchBtn");
				}
			}
			
			if(operation.equals("CANCEL")){
				this.setAllOrderCancelHead(orSrv.getPendingOrders(idSupplier, orderDate, status));
				System.out.println("PENDING ORDER LIST CANCEL: " + this.allOrderCancelHead);
				if(this.allOrderCancelHead.isEmpty()){
					this.comAssist.generateInfoMsg("No Existen Pedidos con estado Pendiente", "actionform:orCancelSearchBtn");
				}
			}

			
		}catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());
			
			log.error(e);
		}
		
	}
	
	public void retrieveOrderDet(Long idHead, String operation){
		
		try{
			if(operation.equals("QUERY")){
				this.setAllOrderQueryDet(orSrv.getOrderDetByHeadId(idHead));
				System.out.println("QUERY ORDER DET: " + this.allOrderQueryDet);
			}
			if(operation.equals("CONFIRM")){
				this.setAllOrderConfDet(orSrv.getOrderDetByHeadId(idHead));
				System.out.println("CONFIRM ORDER DET: " + this.allOrderConfDet);
			}
			if(operation.equals("CANCEL")){
				this.setAllOrderCancelDet(orSrv.getOrderDetByHeadId(idHead));
				System.out.println("CANCEL ORDER DET: " + this.allOrderCancelDet);
			}
			
		}catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());
			
			log.error(e);
		}
	}
	
	public void confirmOrder() throws SQLException{
		try{
			Boolean noneSelected = true;
			Iterator<OrderHeadBean> it = allOrderConfHead.iterator();
			
			while(it.hasNext()){
				OrderHeadBean next = it.next();
				if(next.getSelected() == true){
					noneSelected = false;
					this.orSrv.confirmOrder(next.getId());
				}
				if(!it.hasNext()){
					this.comAssist.generateInfoMsg(
							"Comfirmaci�n realizada con �xito!",
							"actionform:confOrderBtn");
				}
			}
			
			if(noneSelected == true){
				this.comAssist.generateErrorMsg("Favor seleccione al menos un registro", "actionform:confOrderBtn");
			}else{
				this.retrievePendingOrders(this.getOrderConfHead(), "CONFIRM");
			}

			
		}catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());
			
			log.error(e);
		}
		
	}
	
	public void cancelOrder() throws SQLException{
		try{
			Boolean noneSelected = true;
			Iterator<OrderHeadBean> it = allOrderCancelHead.iterator();
			
			while(it.hasNext()){
				OrderHeadBean next = it.next();
				if(next.getSelected() == true){
					noneSelected = false;
					this.orSrv.cancelOrder(next.getId());
				}
				if(!it.hasNext()){
					this.comAssist.generateInfoMsg(
							"Anulaci�n realizada con �xito!",
							"actionform:cancelOrderBtn");
				}
			}
			
			if(noneSelected == true){
				this.comAssist.generateErrorMsg("Favor seleccione al menos un registro", "actionform:cancelOrderBtn");
			}else{
				this.retrievePendingOrders(this.getOrderCancelHead(), "CANCEL");
			}

			
		}catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());
			
			log.error(e);
		}
		
	}
	

	/**
	 *  Retrieve Data for updating. 
	 */
	public void dataToEdit(Long id){
		System.out.println("id = " + id.toString());
		
	}
	
	public void dataToEditUpd() throws ParseException{
		
	}
	
	// falta el metodo void dataToDelete(Long id)
    
	
	
	/**
	 *  ACCESORS AND MUTATORS. 
	 */
	public FacesMessages getFacesMessages() {
		return facesMessages;
	}

	public void setFacesMessages(FacesMessages facesMessages) {
		this.facesMessages = facesMessages;
	}

	public Log getLog() {
		return log;
	}

	public void setLog(Log log) {
		this.log = log;
	}

	public ServiceSqlMap getSqlMap() {
		return sqlMap;
	}

	public void setSqlMap(ServiceSqlMap sqlMap) {
		this.sqlMap = sqlMap;
	}

	public boolean isEditMode() {
		return editMode;
	}

	public void setEditMode(boolean editMode) {
		this.editMode = editMode;
	}

	public String getInitVar() {
		return initVar;
	}

	public void setInitVar(String initVar) {
		this.initVar = initVar;
	}
	
	public UsersBean getUser() {
		return user;
	}

	public void setUser(UsersBean user) {
		this.user = user;
	}
	public BuyConditionBean getBuyCondition() {
		return buyCondition;
	}
	public void setBuyCondition(BuyConditionBean buyCondition) {
		this.buyCondition = buyCondition;
	}
	public BuyConditionServices getBcSrv() {
		return bcSrv;
	}
	public void setBcSrv(BuyConditionServices bcSrv) {
		this.bcSrv = bcSrv;
	}
	public Collection<BuyConditionBean> getAllBuyCondition() {
		return allBuyCondition;
	}
	public void setAllBuyCondition(Collection<BuyConditionBean> allBuyCondition) {
		this.allBuyCondition = allBuyCondition;
	}
	public OrderHeadBean getOrderHead() {
		return orderHead;
	}
	public void setOrderHead(OrderHeadBean orderHead) {
		this.orderHead = orderHead;
	}
	public OrderDetBean getOrderDet() {
		return orderDet;
	}
	public void setOrderDet(OrderDetBean orderDet) {
		this.orderDet = orderDet;
	}
	
	public List<OrderDetBean> getAllOrderDet() {
		return allOrderDet;
	}

	public void setAllOrderDet(List<OrderDetBean> allOrderDet) {
		this.allOrderDet = allOrderDet;
	}

	public Boolean getCanSave() {
		return canSave;
	}
	public static void setCanSave(Boolean arg) {
		canSave = arg;
	}

	public OrderHeadBean getOrderQueryHead() {
		return orderQueryHead;
	}

	public void setOrderQueryHead(OrderHeadBean orderQueryHead) {
		this.orderQueryHead = orderQueryHead;
	}

	public OrderDetBean getOrderQueryDet() {
		return orderQueryDet;
	}

	public void setOrderQueryDet(OrderDetBean orderQueryDet) {
		this.orderQueryDet = orderQueryDet;
	}

	public Collection<OrderHeadBean> getAllOrderQueryHead() {
		return allOrderQueryHead;
	}

	public void setAllOrderQueryHead(Collection<OrderHeadBean> allOrderQueryHead) {
		this.allOrderQueryHead = allOrderQueryHead;
	}

	public Collection<OrderDetBean> getAllOrderQueryDet() {
		return allOrderQueryDet;
	}

	public void setAllOrderQueryDet(Collection<OrderDetBean> allOrderQueryDet) {
		this.allOrderQueryDet = allOrderQueryDet;
	}

	public OrderHeadBean getOrderCancelHead() {
		return orderCancelHead;
	}

	public void setOrderCancelHead(OrderHeadBean orderCancelHead) {
		this.orderCancelHead = orderCancelHead;
	}

	public OrderDetBean getOrderCancelDet() {
		return orderCancelDet;
	}

	public void setOrderCancelDet(OrderDetBean orderCancelDet) {
		this.orderCancelDet = orderCancelDet;
	}

	public Collection<OrderHeadBean> getAllOrderCancelHead() {
		return allOrderCancelHead;
	}

	public void setAllOrderCancelHead(Collection<OrderHeadBean> allOrderCancelHead) {
		this.allOrderCancelHead = allOrderCancelHead;
	}

	public Collection<OrderDetBean> getAllOrderCancelDet() {
		return allOrderCancelDet;
	}

	public void setAllOrderCancelDet(Collection<OrderDetBean> allOrderCancelDet) {
		this.allOrderCancelDet = allOrderCancelDet;
	}

	public OrderHeadBean getOrderConfHead() {
		return orderConfHead;
	}

	public void setOrderConfHead(OrderHeadBean orderConfHead) {
		this.orderConfHead = orderConfHead;
	}

	public OrderDetBean getOrderConfDet() {
		return orderConfDet;
	}

	public void setOrderConfDet(OrderDetBean orderConfDet) {
		this.orderConfDet = orderConfDet;
	}

	public Collection<OrderHeadBean> getAllOrderConfHead() {
		return allOrderConfHead;
	}

	public void setAllOrderConfHead(Collection<OrderHeadBean> allOrderConfHead) {
		this.allOrderConfHead = allOrderConfHead;
	}

	public Collection<OrderDetBean> getAllOrderConfDet() {
		return allOrderConfDet;
	}

	public void setAllOrderConfDet(Collection<OrderDetBean> allOrderConfDet) {
		this.allOrderConfDet = allOrderConfDet;
	}

	public Boolean getSelectedAll() {
		return selectedAll;
	}

	public void setSelectedAll(Boolean selectedAll) {
		this.selectedAll = selectedAll;
	}

	public modalSelectHolder getSelectHolder() {
		return selectHolder;
	}

	public void setSelectHolder(modalSelectHolder selectHolder) {
		this.selectHolder = selectHolder;
	}

	public HtmlDatascroller getScroller() {
		return scroller;
	}

	public void setScroller(HtmlDatascroller scroller) {
		this.scroller = scroller;
	}

	public Integer getScrollerPage() {
		return scrollerPage;
	}

	public void setScrollerPage(Integer scrollerPage) {
		this.scrollerPage = scrollerPage;
	}

	public Boolean getValidateEntireForm() {
		return validateEntireForm;
	}

	public void setValidateEntireForm(Boolean validateEntireForm) {
		this.validateEntireForm = validateEntireForm;
	}
	
	
}
